import { ref, computed, unref, Ref } from 'vue';
//枚举
export enum tabStateEnum {
  TABNUM,
}

//枚举 ts自动推导出来的Language如下
// {
//   '0': 'English',
//   '1': 'Spanish',
//   '2': 'Russian',
//   English: 0,    
//   Spanish: 1,    
//   Russian: 2     
// }


export function valTime(num = 60) {
  const timeNum = ref(num)
  let timer: any = null
  const tolNum = num
  function setTime() {
    if (timer) {
      clearInterval(timer)
    }
    timer = setInterval(() => {
      if (timeNum.value > 0 && timeNum.value <= tolNum) {
        timeNum.value--
      } else {
        timeNum.value = tolNum
        clearInterval(timer)
      }
    }, 1000)

  }
  return { setTime, timeNum, tolNum }
}



const tabState = ref(tabStateEnum.TABNUM);
export function useTabState() {

  function setTabState(state: tabStateEnum) {
    tabState.value = state;
  }

  const getTabState = computed(() => tabState.value);

  return { setTabState, getTabState };
}

export function useFormValid<T extends Object = any>(formRef: Ref<any>) {
  // 获取form对象,做验证
  async function validForm() {
    const form = unref(formRef);
    if (!form) return;
    // form.validate正确返回输入的对象，错误返回错误对象
    const data = await form.validate();
    return data as T;
  }

  return { validForm };
}

export function useFormRules() {
  const getPhoneFormRule = computed(() => createRule('请输入手机号'));
  const getCodeFormRule = computed(() => createRule('请输入验证码'));
  const formState = ref(0)
  //  [k: string] 可索引类型
  const getVeriFormRules = computed(() => {
    // 手机验证
    const phoneFormRule = unref(getPhoneFormRule);
    const codeFormRule = unref(getCodeFormRule);
    if (formState.value === 1) {
      return {
        phone: phoneFormRule,
        code: codeFormRule
      };
    }
    return {
      phone: phoneFormRule,
    };
  });


  function setFormState(num = 0) {
    formState.value = num
  }
  return { getVeriFormRules, setFormState };
}

function createRule(message: string) {
  return [
    {
      required: true,
      message,
      trigger: 'change',
    },
  ];
}
